import dayjs from "dayjs";
import { getKline, getKlineCodes, getKlinesByCode, saveKlines } from "../dao/kline";
import { Kline } from "../entitys/Kline";
import { getAllQtClist, getQtClist, getQtKlines } from "../http/api/east-money";
import { formatKLineStrToKLineObj } from "./format";
import { closeProxy, getProxyAgent, startProxy } from "./proxy";
import { isNil } from "lodash";
import { loop } from "./loop";
import { getInfos } from "../dao/info";

const MarketMap: any = {
  SZ: "0",
  SH: "1",
  BJ: "0",
};
export const saveKlinesByEastMoney = async ({
  secid,
}: any): Promise<boolean> => {
  try {
    const [_, code] = secid.split(".");

    const qtData = await getQtKlines(secid, await getProxyAgent());
    const { dktotal, klines } = qtData.data.data;
    const existedKLines = await getKlinesByCode(code).then((data) =>
      data.map(({ date }) => date)
    );

    const insertKLines: Kline[] = [];
    klines?.forEach((str: string) => {
      const kline: any = formatKLineStrToKLineObj(str);

      const formatDate = dayjs(kline.date).format("YYYYMMDD");
      if (!existedKLines.includes(formatDate)) {
        insertKLines.push({ ...kline, code, date: formatDate } as Kline);
      }
    });
    if (insertKLines?.length) {
      await saveKlines(insertKLines);
      console.log(
        `股票${secid}:插入${insertKLines?.length}条数据成功，共${dktotal}条数据`
      );
      return true;
    } else {
      console.log(`股票${secid}:没有数据需要插入`);
      return true;
    }
  } catch (e) {
    console.log(`股票${secid}:插入失败`);
    return false;
  }
};

export const saveAllKlinesByEastMoney = async () => {
  const existedCodes = (await getKlineCodes()).map(({code})=>code);
  
  const infos = await getInfos();
  const secids = infos
    .filter(({ uniCode }) => !existedCodes.includes(uniCode))
    .map(({ uniCode, exchangeId }) => `${MarketMap[exchangeId!]}.${uniCode}`);

  console.log(`${secids?.length}只需要更新K线数据`);
  await startProxy();
  await loop(secids,10, async (secid: string) => {
    const flag = await saveKlinesByEastMoney({ secid });
  });
  await closeProxy();
};
